// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	async cardslistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let orid = this.userinfo.departmentid;

		let data = await this.model('or_card')
				.where({departmentid:orid, isdisabled:zt, 'name|remarks|price':['like','%'+search+'%']})
				.page(pages, limits)
				.order('id DESC')
				.countSelect();

		return this.json(data);

	}
	
	//新增卡项
	async addcardAction(){
		let data = JSON.parse(this.post('data'));
		let repeatName = await this.model().query('select * from `think_or_card` where name = \''+data.name+'\' and departmentid='+this.userinfo.departmentid);
		if (!think.isEmpty(repeatName)) {
			return this.fail('新建VIP卡名称重复！');
		}
		let model = this.model('or_card');
		await model.transaction(async() => {
			try {
				let carddata = {
					name: data.name,
					remarks: data.remarks,
					departmentid: this.userinfo.departmentid,
					typeid: data.type,
					price: data.price,
					validity: data.type == 1 ? data.validity : 0,
					addtime: Math.round(Date.now()/1000),
					isdisabled: data.radio,
				}
				let adcardid = await model.add(carddata);
				let adsubjs = 1;
				if (data.tableData.length) {
					let adsubjects = []
					data.tableData.forEach((row) => {
						adsubjects.push({
							cardid : adcardid,
							subjectid : row.id,
							num : data.type == 1 ? 0 : row.num,
							price : row.price
						})
					})
					adsubjs = await this.model('or_cardsubject').db(model.db()).addMany(adsubjects);
				}
				if (adcardid && adsubjs) {
					model.commit();
					return this.success({info:'添加成功'});
				}
			} catch(e) {
				console.log(e);
				model.rollback();
				return this.fail('添加失败');
			}
		})
	}

	//编辑卡项
	async editcardAction(){
		if (this.isPost) {
			let data = JSON.parse(this.post('data'));
			let repeatName = await this.model().query('select * from `think_or_card` where name = \''+data.name+'\' and departmentid='+this.userinfo.departmentid+' and id != '+data.id);
			if (!think.isEmpty(repeatName)) {
				return this.fail('VIP卡名称重复！');
			}

			// 如果店家拉取了机构卡项，则机构卡项不能编辑项目
			let shop_id = await this.model('or_department').where({pid:this.userinfo.departmentid,isdisable:0}).getField('id');
			let isEdit = await this.model('or_shop_card').where({cardid:data.id,shopid:['IN',shop_id]}).find();
			if (!think.isEmpty(isEdit)) {
				return this.fail('此卡已经被使用不能编辑！')
			}

			let model = this.model('or_card');
			await model.transaction(async() => {
				try {
					let carddata = {
						name: data.name,
						remarks: data.remarks,
						typeid: data.type,
						validity: data.type == 1 ? data.validity : 0,
						price: data.price
					}
					let upRes = await model.where({id: data.id}).update(carddata);
					let adsubjects = []
					if (data.tableData.length) {
						data.tableData.forEach((row) => {
							adsubjects.push({
								cardid : data.id,
								subjectid : row.id,
								num : data.type == 1 ? 0 : row.num,
								price : row.price
							})
						})	
					} else {
						model.rollback();
						return this.fail('项目不能为空！');
					}
					// 先删除再添加
					let delRes = await this.model('or_cardsubject').db(model.db()).where({cardid: data.id}).delete()
					let addRes = await this.model('or_cardsubject').db(model.db()).addMany(adsubjects);
					if (upRes && delRes && addRes) {
						model.commit();
						return this.success({info:'编辑成功'});
					}
				} catch(e) {
					model.rollback();
					return this.fail('编辑失败');
				}
			})
		}else{
			let cardid = this.get('id');
			let cardInfo = await this.model('or_card').where({id:cardid}).find();
			let cardList = await this.model('or_cardsubject')
			.alias('cs')
			.field('cs.cardid,cs.subjectid as id,cs.num,cs.price,s.name,s.remarks')
			.join('left join `think_or_subject` s on cs.subjectid = s.id')
			.where({cardid: cardid})
			.select()
			let data = {
				cardInfo: cardInfo,
				cardList: cardList
			}
			return this.json(data);
		}
	}

	//禁用卡以及卡下面的项目和产品
	async unstopAction(){
		let id = this.post('id');
		let st = this.post('st');
		if (st*1) {
			let res = await this.model('or_card').where({id:id}).update({isdisabled:st});
			let _res = await this.model('or_shop_card').where({cardid:id}).update({isdisable:st});
			return false !== res&&false !== _res?this.success('停用成功'):this.fail('停用失败');
		} else {
			let res = await this.model('or_card').where({id:id}).update({isdisabled:st});
			let _res = await this.model('or_shop_card').where({cardid:id}).update({isdisable:st});
			return false !== res&&false !== _res?this.success('启用成功'):this.fail('启用失败');
		}
	}

	//制作inarray函数
	inArray(id,array){
		if (!think.isEmpty(array)) {
			for (var i = 0; i < array.length; i++) {
				if (array[i] == id) {
					return i;
				};
			};
		};
		return false;
	}
	// 如果当前项目被下属分店拉取，则机构不能操作当前项目
	async ispull(cardid){
		let isuse = await this.model('or_shop_card').where({cardid: cardid}).select();
		if (!think.isEmpty(isuse)) return {msg:'当前项目以被分店拉取'};
		else return false;
	}
}